package cn.sanch.user.controller;

import cn.sanch.basic.util.AjaxResult;
import cn.sanch.basic.util.BusinessException;
import cn.sanch.user.dto.BinderDto;
import cn.sanch.user.dto.LoginDto;
import cn.sanch.user.service.ILogininfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 接口类：登录
 * @author sanch37
 * 2022/6/8
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILogininfoService logininfoService;


    /**
     * 接口：账号登录
     * @return
     */
    @PostMapping("/account")

    public AjaxResult accountLogin(@RequestBody LoginDto loginDto) {

        try {

            Map<String, Object> map = logininfoService.accountLogin(loginDto);
            return AjaxResult.me().setResultObj(map);

        } catch (BusinessException b) {
            b.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("登录失败：" + b.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后再试！");
        }
    }


    /**
     * 接口：微信扫码登录
     * @return
     */
    @GetMapping("/wechat/{code}")
    public AjaxResult wechatLogin(@PathVariable("code") String code) {

        try {

            return logininfoService.wechatLogin(code);

        } catch (BusinessException b) {
            b.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("微信扫码登录失败：" + b.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后再试！");
        }
    }

    /**
     * 接口：微信扫码登录绑定手机
     * @return
     */
    @PostMapping("/wechat/binder")
    public AjaxResult wechatBinder(@RequestBody BinderDto binderDto) {

        try {

            return logininfoService.wechatBinder(binderDto);

        } catch (BusinessException b) {
            b.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("绑定失败：" + b.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后再试！");
        }
    }

    /**
     * 接口：退出登录
     * @param token
     * @return
     */
    @GetMapping("/logout/{token}")
    public AjaxResult logout(@PathVariable("token") String token) {

        try {
            logininfoService.logout(token);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后再试！");
        }
    }

}
